package cc.higou.service;

import cc.higou.core.dao.SkuMapper;
import cc.higou.core.pojo.Cart;
import cc.higou.core.pojo.Item;
import cc.higou.core.pojo.SuperPojo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.util.List;

@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private Jedis jedis;

    @Override
    public Cart fillItemsSkus(Cart cart) {
        //更具传递过来的cart对象查询相关的商品详情
        if (cart == null) {
            return null;
        }
        List<Item> list = cart.getItems();
        for (Item item : list) {
            SuperPojo superPojo = skuMapper.findSkuAndColorAndProductBySkuId(item.getSkuId());
            item.setSku(superPojo);
        }
        return cart;
    }

    @Override
    public Cart getCartFromRedis(String username) throws IOException {
        String cartJson = jedis.get("cart:" + username);
        ObjectMapper mapper = new ObjectMapper();
        if (cartJson != null) {
            Cart cart = mapper.readValue(cartJson, Cart.class);
            return cart;
        }
        return null;
    }

    @Override
    public void addCartToRedis(String username, Cart cart) throws JsonProcessingException {
        if (cart == null) {
            return;
        }
        ObjectMapper mapper = new ObjectMapper();
        String cartJson = mapper.writeValueAsString(cart);
        //将值存放到redis中
        jedis.set("cart:" + username, cartJson);
    }
}
